import React from 'react';
import '../static/main.css';
import { message } from 'antd';
import * as request from '../utils/request';
import $ from 'jquery'
import go from '../utils/global';

//左侧问答
class Chat extends React.Component{
  constructor(props){
    super(props)
    // console.log(props)
    this.state={
      //聊天内容列表
      items:[],
      //引用内容
      quote:'',
      //是否隐藏引用-默认是
      isHideQuote:'hide',
      //待发送内容
      sendText:'',
      //当前点击的详情按钮uid key(包含搜索结果和问题解析)
      curDetailBtnKey:-1

    }
  }
  
  /////////////////////////////////////////////////生命周期////////////////////////////////////////////////////////////
  componentDidMount(){
    console.log('chat componentDidMount...')

    //聊天框内容初始化
    this.addChatInitMsg()
    // request.post('api/qa/searcher', {"content":"行业研报中传感器及激光雷达出现了多少次"}).then(res => {
    //     console.log(res);
    // })

    //点击详情
    $('#root').on('click', '#Chat .ana-detail>span', function(){
      console.log('#Chat .ana-detail click!!!!')
      $('#Chat .ana-detail.hide').removeClass('hide')
      $(this).parent('.ana-detail').addClass('hide')
    })
  }

  componentDidUpdate(){
    console.log('chat update...')
  }
  /////////////////////////////////////////////////生命周期END////////////////////////////////////////////////////////////



  /////////////////////////////////////////////////子组件////////////////////////////////////////////////////////////
  //切换详情按钮
  toggleDetailBtn = () => {
    //no used
  }

  //追加聊天内容-初始化内容
  addChatInitMsg = (obj) => {
    obj = obj ? obj : {}
    let items = go.copy(this.state.items)
    obj.str = (<p>您好，我是小智！<br/>欢迎使用智能知识库！您可以向我咨询各种问题。</p>)
    let dom = (
      <div className="msg clearfix" key={go.uid()}>
        <span className="triangle"></span>
        <div className="article"> 
          {obj.str}
        </div>
      </div>
    )
    items.push(dom)
    this.setState({items: items});
  }

  //追加聊天内容-发送内容
  addChatMsgBySend = (obj) => {
    obj = obj ? obj : {}
    let items = this.state.items
    let dom = (
      <div className="msg fr" key={go.uid()}>
        <span className="triangle right"></span><div className="article">{obj.str}</div>
        <span className="quote" onClick={(e)=>{this.byQuote(e)}}>引用</span>
      </div>
    )
    items.push(dom)
    this.setState({items: items});
    this.scrollToBottom()
  }

  //追加聊天内容-搜索结果
  addChatMsgBySearchRes = (obj) => {
    obj = obj ? obj : {}
    let items = go.copy(this.state.items)
    //为了将搜索结果tab标题替换为问题解析的标题
    let val_format = obj.parse.text ? obj.parse.text : ''
    request.post('api/qa/searcher', {"content":obj.str,"quote":obj.quote,"parse":obj.parse}).then(res => {
      if(!res.errCode && !$.isEmptyObject(res.data)){
        let uid = go.uid()
        let resText = res.data.answer.text.val
        res.data.answer.text.val_format = val_format
        let dom = (
          <div className="msg clearfix" key={uid} mkey={uid}>
            <span className="triangle"></span>
            <div className="article"> 
              <p>{resText}</p>
              <div className={"ana-detail mbtn"}>
                <span onClick={()=>{this.props.showSearchPage(uid)}}>查看搜索结果</span>
              </div>
            </div>
          </div>
        )
        items.push(dom)
        this.setState({items: items});
        this.scrollToBottom()
        this.props.createSearchData(uid, res.data)
      }

    })

  }

  //追加聊天内容-问题解析
  addChatMsgByParser = (obj) => {
    obj = obj ? obj : {}
    let items = go.copy(this.state.items)
    let dom

    request.post('api/qa/parser', {"content":obj.str,"quote":obj.quote}).then(res => {
        // console.log(res);
        if(!res.errCode && !$.isEmptyObject(res.data)){
          let data = res.data
          let wslot = []
          let uid = go.uid()
          if(data.word_slot && data.word_slot.length){
            let slotData = data.word_slot
            //TODO这里最多展示三个
            for (let skey=0; skey < 3; skey++) {
              if(slotData[skey] && slotData[skey].words.length){
                wslot.push(
                  <div className="ana-list" key={go.uid()}>
                    <span className="tag">{slotData[skey].type_name}</span>
                    <span className={"tag-value "+slotData[skey].type}>{slotData[skey].words[0].text}</span>
                  </div>
                )
              }
            }
          }

          dom = (
            <div className="ana-result" key={uid} mkey={uid}>
              <div className="ana-item">
                <div className="ana-head">
                  <span className="snote">问题解析：</span>
                  <span className="sbnt mbtn">{data.intent_name ? data.intent_name : ''}</span>
                </div>
                <div className="ana-content">
                    {wslot}
                </div>
                <div className={this.state.curDetailBtnKey === uid ? "ana-detail mbtn hide" : "ana-detail mbtn"}>
                  <span onClick={(ele)=>{this.props.showParserPage(uid)}}>查看问题解析</span>
                </div>
              </div>
            </div>
          )
          items.push(dom)

          this.setState({items:items});
          this.scrollToBottom()
          this.props.createParserData(uid, res.data)

          //获取搜索结果
          this.addChatMsgBySearchRes({str:obj.str,"quote":obj.quote,"parse":data})
        }
    })
  }

/////////////////////////////////////////////////子组件 END////////////////////////////////////////////////////////////





/////////////////////////////////////////////////方法////////////////////////////////////////////////////////////
  //获取问题解析数据-弃用
  // getParserData = (obj)=> {
  //   obj = obj ? obj : {}
  //   request.post('api/qa/parser', {"content":obj.str,"quote":obj.quote}).then(res => {
  //       // console.log(res);
  //       if(!res.errCode && !$.isEmptyObject(res.data)){
  //         let data = res.data
  //         this.props.showParserPage(data)
  //       }
  //   })
  // }


  //滑动到底部
  scrollToBottom = ()=> {
    if (this.messagesEnd) {
        const scrollHeight = this.messagesEnd.scrollHeight;//里面div的实际高度  2000px
        const height = this.messagesEnd.clientHeight;  //网页可见高度  200px
        const maxScrollTop = scrollHeight - height; 
        this.messagesEnd.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
      //如果实际高度大于可见高度，说明是有滚动条的，则直接把网页被卷去的高度设置为两个div的高度差，实际效果就是滚动到底部了。
    }
  }

  //输入框变化
  handleChange = (event) => {
    let val = event.target.value
    this.setState({sendText: val});
  }

  //引用
  byQuote = (event) => {
    //获取引用内容
    let text = $(event.target).closest('.msg').find('.article').text()
    this.setState({isHideQuote: '',quote: text})
  }
  //隐藏引用
  hideQuote = (event) => {
    this.setState({isHideQuote: 'hide',quote: ''})
  }

  sendContent=()=>{
    //发送Neri
    let str = this.state.sendText
    let quote = this.state.quote
    if(str === ''){
      message.warning('发送内容不能为空')
      return
    }

    //发送内容
    this.addChatMsgBySend({str:str})

    //获取问题解析
    this.addChatMsgByParser({str:str,quote:quote})

    //清空输入框
    this.setState({sendText: '', items:this.state.items});

    //删除引用
    if(quote !== ''){
      this.hideQuote()
    }
  }

  /////////////////////////////////////////////////方法 END////////////////////////////////////////////////////////////

  render () {
    return (
      <div id="col-l">
        <div className="col-l-t" ref={(el) => { this.messagesEnd = el }}>
          <div className="content">
            <div className="bubble" id="Chat">{this.state.items}</div>
          </div>
        </div>
        <div className="col-l-b">
          <div className="faq-input-content">
            <div className={"cite "+this.state.isHideQuote}><span className="cut">引用：{this.state.quote}</span><em className="close-btn" onClick={()=>{this.hideQuote()}}>×</em></div>
            <textarea className="input" name="textfield"  id="faqInput" placeholder="请输入..." autoComplete="off" onChange={(e)=>{this.handleChange(e)}} value={this.state.sendText}></textarea>
            <input type="button" className="mbtn" value="发送" onClick={this.sendContent} />
            <div className="input-count"><span id="textCount"></span></div>
          </div>
        </div>
      </div>
    );
  }
}

export default Chat